<?php
namespace app\admin\controller;

use app\admin\controller\Base;
use think\Loader;
use think\Db;
use think\Request;
use think\Session;

class User extends Base
{
    /**
     *会员列表
     * @return mixed
     */
    public function UserList()
    {
        //条件查询
        $Data = Param();
        if (empty($Data)){
            $Data = [
                'level' => 0,
                'name' => '',
                'phone' => '',
                'username' => '',
                'begin_time' => '',
                'end_time' => '',
                'id' => '',
            ];

        }

        $this->assign('Data',$Data);
        $Where = [];
        //等级查询
        if($Data['level'] > 0){
            $Where['level'] = $Data['level'];
        }

        if($Data['id'] != ''){
            $Where['id'] = $Data['id'];
        }else{
            $Where['id'] = array('neq',1);
        }

        //会员姓名查询
        if($Data['name'] != ''){
            $Where['name'] = array('like','%'.$Data['name'].'%');

        }

        //手机号码查询
        if($Data['phone'] != ''){
            $Where['phone'] = array('like','%'.$Data['phone'].'%');
        }

        //会员账号查询
        if($Data['username'] != ''){
            $Where['username'] = array('like','%'.$Data['username'].'%');
        }

        //时间查询
        if($Data['begin_time'] != '' && $Data['end_time'] == ''){   //只有开始时间没有结束时间
           $BeginTime = strtotime($Data['begin_time']);
           $Where['add_time'] = array('egt',$BeginTime );
        }

        if($Data['begin_time'] == '' && $Data['end_time'] != ''){   //只有结束时间没有开始时间
            $EndTime = strtotime($Data['end_time']);
            $Where['add_time'] = array('elt',$EndTime );
        }

        if($Data['begin_time'] != '' && $Data['end_time'] != ''){   //有开始时间有结束时间
            $BeginTime = strtotime($Data['begin_time']);
            $EndTime = strtotime($Data['end_time']);
            $Where['add_time'] = array(array('egt',$BeginTime ),array('elt',$EndTime ));
        }

//        $Where['id'] = array('neq',1);
        //总记录条数
        $Count = UserCount($Where);
        $this->assign('Count', $Count);

        //会员信息
        $UserList = UserList($Where);
        $this->assign('UserList', $UserList['UserList']);

        //分页
        $this->assign('Page', $UserList['Page']);

        //级别信息
        $LevelList = LevelList();
        $this->assign('LevelList', $LevelList);

        return $this->fetch('UserList');
    }

    /**
     * 后台添加会员
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function UserAdd(){
        if(IsPost()){
            $Data = Param();

            //账号是否存在
            $UserInfo = UserInfo(['username'=>$Data['username']]);
            if(!empty($UserInfo)){
                return ['status'=>0,'message'=>'会员账号已存在'];
            }

            //推荐账号是否存在
            $RecommendInfo = UserInfo(['username'=>$Data['recommend']]);
            if(empty($RecommendInfo)){
                return ['status'=>0,'message'=>'推荐账号不存在'];
            }
            $Data['recommend'] = $RecommendInfo['id'];
            $Data['password_login'] = md5($Data['password_login']);
            $Data['password_pay'] = md5($Data['password_pay']);
            $Data['add_time'] = time();
            $Data['status'] = 1; //激活状态 0未激活 1已激活 免费注册无需激活



            if(Db::name('user')->insert($Data)){
                //新添加的会员信息
                $UserInfo = UserInfo(['username'=>$Data['username']]);
                //创建推荐关系
                Db::query('call add_user_recommend(:id,:recommend_id)',['id'=>$UserInfo['id'],'recommend_id'=>$Data['recommend']]);
                $yuan = Db::name('shun')->order('id desc')->find();
                $shun = explode(',',$yuan['str']);
//            //将移除的用户添加到末尾
                array_push($shun,$UserInfo['id']);//添加元素
//            //将顺序转化为字符串存起来
                $str = implode(',',$shun);
                Db::name('shun')->where(['id'=>$yuan['id']])->update(['str'=>$str]);

                return ['status'=>1,'message'=>'添加成功'];
            }else{
                return ['status'=>0,'message'=>'系统错误，请重试'];
            }

        }
        //级别信息
        $LevelList = LevelList();
        $this->assign('LevelList',$LevelList);

        //新用户名
//        $this->assign('NewUsername',randNumber(12));

        return $this->fetch('UserAdd');
    }

    /**
     * 会员开通
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function UserStatus(){
        //Post请求操作
        if(IsPost()){
            //会员信息
            $UserInfo = UserInfo(['id'=>Param('id')]);
            if($UserInfo['status'] == 1){
                return ['status'=>0,'message'=>'该会员已激活，请勿重复操作'];
            }

            //推荐人信息
            $RecommendInfo = UserInfo(['username'=>$UserInfo['recommend']]);
            if(empty($RecommendInfo)){
                return ['status'=>2,'message'=>'该账号没有推荐账号或推荐账号不存在，不能激活'];
            }

            //更新会员状态
            if(Db::name('user')->where(['id'=>$UserInfo['id']])->update(['status'=>1,'open_time'=>time()])){
                //结算业绩
                Db::query('call execute_now()');

                return ['status'=>1,'message'=>'开通成功'];
            }else{
                return ['status'=>0,'message'=>'系统错误，请重试'];
            }
        }
    }

    /**
     * 会员信息编辑
     * @return array|mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function UserEdit(){
        $UserInfo = UserInfo(['id'=>Param('id')]);
        $UserInfo['recommend_id'] = UserInfo(['id'=>$UserInfo['recommend']])['username'];
        //查看当前用户有没有下级   有下级不能改推荐人
        $downinfo = UserInfo(['recommend'=>$UserInfo['id']]);
        $this->assign('downinfo',$downinfo);
        //Post请求操作
        if(IsPost()){
            //请求数据
            $Data = Param();

            if($Data['recommend'] == ''){
                return ['status'=>0,'message'=>'推荐账号不能为空'];
            }

            $pd = Db::name('user')->where(['quyu'=>$Data['quyu'],'id'=>['neq',$UserInfo['id']]])->find();
            if($pd['quyu'] != ''){
                return ['status'=>0,'message'=>'该地区已有人管理,请重新输入'];
            }
            if(!empty($Data['recommend'])){
                $RecommendInfo = UserInfo(['id'=>$Data['recommend']]);
                if(empty($RecommendInfo)){
                    return ['status'=>0,'message'=>'推荐账号不存在'];
                }elseif($RecommendInfo['id'] == $UserInfo['id']){
                    return ['status'=>0,'message'=>'推荐人不能是自己'];
                }else{
                    $Data['recommend'] = $RecommendInfo['id'];
                }
            }

//$a = Db::name('user')->where(['id'=>['gt',1]])->column('id');
//            $str = implode(',',$a);
//            var_dump($str);die;

            //向表中添加数据
            if(Db::name('user')->where(['id'=>$UserInfo['id']])->update($Data) !== false){
                if($UserInfo['recommend'] != $Data['recommend']){
                    //判断是否是单线修改
                    $where['user_id'] = $Data['recommend'];
                    //将所有上级id取出
                    $ids= Db::name('user_recommend')->where($where)->column('recommend_id');
//            var_dump($ids);die;
                    //判断修改人是否在这个id中   在的话说明往后改
                    if(in_array($UserInfo['id'],$ids)){
                        //在
                        //单线往后改   需要改动自己的推荐人   原本下一级的推荐人(紧缩)
                        //键值互换
                        $ids_1 = array_flip($ids);
                        //拿到当前用户的键
                        $a = $ids_1[$UserInfo['id']];
                        //键不可能小于0
                        if($a -1 >= 0){
                            //找到修改用户的同线下级
                            $downid = $ids[$a - 1];
                            //修改用户的原推荐人
                            $upid = $UserInfo['recommend'];
                            //将同线下级用户的推荐人  改为  修改用户的原推荐人
                            Db::name('user')->where(['id'=>$downid])->update(['recommend'=>$upid]);
                        }
                        //存顺序
                        //取出之前的顺序
                        $yuan = Db::name('shun')->order('id desc')->find()['str'];
                        $shun = explode(',',$yuan);
                        //键值互换
                        $shun_1 = array_flip($shun);
                        //移除往后移动的用户
                        unset($shun_1[$UserInfo['id']]);
                        //键值互换
                        $shun_2 = array_flip($shun_1);
                        //将移除的用户添加到末尾
                        array_push($shun_2,$UserInfo['id']);//添加元素
                        //将顺序转化为字符串存起来
                        $str = implode(',',$shun_2);
                        Db::name('shun')->insert(['str'=>$str]);
                        Db::name('user_recommend')->where(['id'=>['gt',1]])->delete();
                        foreach ($shun_2 as $v){
                            $info = UserInfo(['id'=>$v]);
                            if($info){
                                $user_id = $info['id'];
                                $recommend_id = $info['recommend'];
                                Db::query('call add_user_recommend(:id,:recommend_id)',['id'=>$user_id,'recommend_id'=>$recommend_id]);
                            }

                        }

                    }else{
                        //不在   说明往前  或者跨分支改的
                        //取出之前的顺序
                        $yuan = Db::name('shun')->order('id desc')->find()['str'];
                        $shun = explode(',',$yuan);
                        //键值互换
                        $shun_1 = array_flip($shun);
                        //获取团队受影响的所有人
                        $team_ids= Db::name('user_recommend')->where(['recommend_id'=>$UserInfo['id']])->column('user_id');
                        //移除往前移动的用户
                        if($team_ids){
                            foreach ($team_ids as $v){
                                //移除受影响得人
                                unset($shun_1[$v]);
                            }
                        }
                        //键值互换
                        $shun_2 = array_flip($shun_1);
                        //插入
                        if($team_ids){
                            foreach ($team_ids as $val){
                                //将移除的用户添加到末尾
                                array_push($shun_2,$val);//添加元素
                            }
                        }
                        //将顺序转化为字符串存起来
                        $str = implode(',',$shun_2);
                        Db::name('shun')->insert(['str'=>$str]);
                        Db::name('user_recommend')->where(['id'=>['gt',1]])->delete();
                        foreach ($shun_2 as $v){
                            $info = UserInfo(['id'=>$v]);
                            if($info){
                                $user_id = $info['id'];
                                $recommend_id = $info['recommend'];
                                Db::query('call add_user_recommend(:id,:recommend_id)',['id'=>$user_id,'recommend_id'=>$recommend_id]);
                            }

                        }
                    }
                }

                return ['status'=>1,'message'=>'修改成功'];
            }else{
                return ['status'=>0,'message'=>'系统错误，请重试'];
            }
        }
        $LevelList = LevelList();
        $this->assign('LevelList',$LevelList);
        $this->assign('UserInfo',$UserInfo);

        return $this->fetch('UserEdit');
    }

    /**
     * 余额修改
     * @return mixed
     */
    public function UserBalance(){
        //会员信息
        $UserInfo = UserInfo(['id'=>Param('id')]);

        //Post请求
        if(IsPost()){
            //请求数据
            $Data = Param();
            if($Data['reward_type'] == 1){ //增加

                $UserSave['balance_'.$Data['type']] = $UserInfo['balance_'.$Data['type']] + $Data['num'];
                // $Remarks = '后台增加';
                $Remarks = $Data['Remarks'];

            }elseif($Data['reward_type'] == 2){    //减少

                $UserSave['balance_'.$Data['type']] = $UserInfo['balance_'.$Data['type']] - $Data['num'];
                // $Remarks = '后台扣除';
                $Remarks = $Data['Remarks'];
            }
            
            //获取管理员id
            $adminid = Session::get('admin_id');

            if(Db::name('user')->where(['id'=>$UserInfo['id']])->update($UserSave)){

                FinanceAdd($UserInfo['id'],$adminid,$Data['num'],$Data['type'],$Data['reward_type'],$Remarks); //增加流水记录

                return ['status'=>1,'message'=>'操作成功'];
            }else{
                return ['status'=>0,'message'=>'系统错误，请重试'];
            }
        }

        $this->assign('UserInfo',$UserInfo);
        $this->assign('Type',Param('type'));
        return $this->fetch('UserBalance');
    }

    /**
     * 重置会员密码
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function UserPassword(){
        //Post请求操作
        if(IsPost()){
            //删除表中数据
            $Save['password_login'] = md5(123456);
            $Save['password_pay'] = md5(123456);
            if(Db::name('user')->where(['id'=>Param('id')])->update($Save)){
                return ['status'=>1,'message'=>'重置成功'];
            }else{
                return ['status'=>0,'message'=>'重置成功'];
            }
        }
    }

    /**
     * 会员删除
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function UserDelete(){
        //Post请求操作
        if(IsPost()){
            //删除表中数据
            $UserInfo = UserInfo(['id'=>Param('id')]);

            //推荐人数
            $RecommendCount = UserCount(['recommend'=>$UserInfo['id']]);
            if($RecommendCount > 0){
                return ['status'=>0,'message'=>'该用户有下级推荐用户，不能删除'];
            }
//            //接点人数
//            $ContactCount = UserCount(['contact'=>$UserInfo['username']]);
//            if($ContactCount > 0){
//                return ['status'=>0,'message'=>'该用户有下级接点用户，不能删除'];
//            }

            //推荐人信息
            $RecommendInfo = UserInfo(['id'=>$UserInfo['recommend']]);
            $RecommendSave['recommend_count'] = $RecommendInfo['recommend_count'] - 1;
//            //接点人信息
//            $ContactInfo = UserInfo(['username'=>$UserInfo['recommend']]);
//            $ContactSave['contact_count'] = $ContactInfo['contact_count'] - 1;

            if(Db::name('user')->where(['id'=>$UserInfo['id']])->delete()){
                Db::name('user')->where(['id'=>$RecommendInfo['id']])->update($RecommendSave);
//                Db::name('user')->where(['id'=>$ContactInfo['id']])->update($ContactSave);
                Db::name('user_recommend')->where(['user_id'=>$UserInfo['id']])->delete();
                Db::name('user_order')->where(['user_id'=>$UserInfo['id']])->delete();
                Db::name('finance')->where(['user_id'=>$UserInfo['id']])->delete();
                Db::name('finance')->where(['from_id'=>$UserInfo['id']])->delete();
                return ['status'=>1,'message'=>'删除成功'];
            }else{
                return ['status'=>0,'message'=>'系统错误，请重试'];
            }
        }
    }

    /**
     * 登录前台
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function UserLogin(){
        if (IsPost()){
            $ID = Param('id');
            //查询结果
            $UserInfo = UserInfo(['id'=>$ID]);

            if(empty($UserInfo)){
                return ['status'=>0,'message'=>'账号不存在'];
            }

            if($UserInfo['status'] == 0){
                return ['status'=>0,'message'=>'账号未激活'];
            }

            if($UserInfo['status'] == 2){
                return ['status'=>0,'message'=>'账号已被停用'];
            }

            Session::set('user_id',$UserInfo['id']);

            return ['status'=>1,'message'=>'登录成功'];
        }
    }

    /**
     * 会员关系生成
     */
    public function UserSettlement(){
        if(IsPost()){
            //存储过程
            if(Db::query('call execute_bind()')){
                return ['status'=>1,'message'=>'生成完成'];
            }else{
                return ['status'=>0,'message'=>'系统错误，请重试'];
            }
        }

    }

    /**
     * 会员导入
     * @return mixed
     */
    public function UserImport()
    {

        return $this->fetch('UserImport');
    }

    /**
     * Excel导入
     */
    public function ExcelImport()
    {
        Loader::import('PHPExcel.PHPExcel');
        Loader::import('PHPExcel.PHPExcel.IOFactory.PHPExcel_IOFactory');
        Loader::import('PHPExcel.PHPExcel.Reader.Excel5');
        //获取表单上传文件
        $file = request()->file('file');
        $info = $file->validate(['ext' => 'xlsx,xls'])->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'excle');
        if ($info) {
            if (empty($info)) {
                return error('导入失败!');
            }
            $exclePath = $info->getSaveName();  //获取文件名
            //上传文件的地址
            $filename = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'excle' . DS . $exclePath;
            //判断版本，这里有的网上的版本没有进行判断，导致会报大概这样的错误：
            //Warning: ZipArchive::getFromName() [ziparchive.getfromname]: Invalid or unitialized ，这里加上这个判断就可以了
            $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
            if ($extension == 'xlsx') {
                $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
                //加载文件内容,编码utf-8
                $objPHPExcel = $objReader->load($filename, $encode = 'utf-8');
            } else if ($extension == 'xls') {
                $objReader = \PHPExcel_IOFactory::createReader('Excel5');
                $objPHPExcel = $objReader->load($filename, $encode = 'utf-8');
            } else {
                return ['status' => 0, 'message' => '请上传excel格式的文件!'];
            }
            $excel_array = $objPHPExcel->getsheet(0)->toArray();   //转换为数组格式
            array_shift($excel_array);  //删除第一个数组(标题);
            $data = [];

            // echo "<pre>";
            // var_dump($excel_array);die;

            foreach ($excel_array as $k => $v) {
                
                //data数组根据你表字段自行修改，这里Excel文件里的字段要跟表一致
                //查询要修改的订单
                $orderinfo = Db::name('user_order')->where(['order_id'=>$v[0]])->find();
                if(!$orderinfo){
                    $hang = $k + 2;
                    return ['status' => 0, 'message' => '第'.$hang.'行订单号不存在!'];
                }
                
                if($v[11] == null || $v[12] == null){
                    $data['express_name']= $v[11];
                    $data['express_num'] = $v[12];
                    $data['status'] = 1;
                }else{
                    $data['express_name']= $v[11];
                    $data['express_num'] = $v[12];
                    $data['status'] = 2;
                }
                
                Db::name('user_order')->where(['id'=>$orderinfo['id']])->update($data);
            }
            // if (Db::name('user')->insertAll($data)) {//批量插入数据

            //     return ['status' => 1, 'message' => '导入数据成功!'];
            // }else{

            //     return ['status' => 0, 'message' => '导入数据失败!'];

            // }
            return ['status' => 1, 'message' => '导入数据成功!'];
        } else {
            return ['status' => 0, 'message' => '获取文件失败!'];
        }
    }

    //生成代理
    public function make()
    {
        $List = Db::name('china')->where(['p_id' => 0])->select();

        foreach ($List as $k => $v) {  //添加省代理
            $AddProvince = [
                'username' => "H" . $List[$k]['id'],
                'password_login' => md5(123456),
                'title' => $List[$k]['name'] . '分公司',
                'level' => 1,
                'contact' => 'admin',
                'add_time' => time()
            ];
            Db::name('user')->insert($AddProvince);

            $List_city = Db::name('china')->where(['p_id' => $List[$k]['id']])->select();
            foreach ($List_city as $kk => $vv) {  //添加市代理
                $AddCity = [
                    'username' => "H" . $List_city[$kk]['id'],
                    'password_login' => md5(123456),
                    'title' => $List_city[$kk]['name'] . '分公司',
                    'level' => 3,
                    'contact' => $AddProvince['username'],
                    'add_time' => time()
                ];
                Db::name('user')->insert($AddCity);

                $List_area = Db::name('china')->where(['p_id' => $List_city[$kk]['id']])->select();
                foreach ($List_area as $kkk => $vvv) {  //添加区代理
                    $AddArea = [
                        'username' => "H" . $List_area[$kkk]['id'],
                        'password_login' => md5(123456),
                        'title' => $List_area[$kkk]['name'] . '分公司',
                        'level' => 4,
                        'contact' => $AddCity['username'],
                        'add_time' => time()
                    ];
                    Db::name('user')->insert($AddArea);
                }
            }
        }
    }

    /**
     * 会员表导出
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     * @throws \PHPExcel_Writer_Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function UserExport(){

        //条件查询
        $Data = Param();
        $Where = [];
        //等级查询
        if($Data['level'] > 0){
            $Where['level'] = $Data['level'];
        }

        //会员姓名查询
        if($Data['name'] != ''){
            $Where['name'] = array('like','%'.$Data['name'].'%');

        }

        //手机号码查询
        if($Data['phone'] != ''){
            $Where['phone'] = array('like','%'.$Data['phone'].'%');
        }

        //会员账号查询
        if($Data['username'] != ''){
            $Where['username'] = array('like','%'.$Data['username'].'%');
        }

        //时间查询
        if($Data['begin_time'] != '' && $Data['end_time'] == ''){   //只有开始时间没有结束时间
            $BeginTime = strtotime($Data['begin_time']);
            $Where['add_time'] = array('egt',$BeginTime );
        }

        if($Data['begin_time'] == '' && $Data['end_time'] != ''){   //只有结束时间没有开始时间
            $EndTime = strtotime($Data['end_time']);
            $Where['add_time'] = array('elt',$EndTime );
        }

        if($Data['begin_time'] != '' && $Data['end_time'] != ''){   //有开始时间有结束时间
            $BeginTime = strtotime($Data['begin_time']);
            $EndTime = strtotime($Data['end_time']);
            $Where['add_time'] = array(array('egt',$BeginTime ),array('elt',$EndTime ));
        }

        $xlsData = Db('user')->where($Where)->select();

        Loader::import('PHPExcel.PHPExcel');
        Loader::import('PHPExcel.PHPExcel.Worksheet.Drawing');
        Loader::import('PHPExcel.PHPExcel.Writer.Excel2007');
        $objExcel = new \PHPExcel();
        $objWriter = \PHPExcel_IOFactory::createWriter($objExcel, 'Excel2007');

        $objActSheet = $objExcel->getActiveSheet();
        $key = ord("A");
        $letter =explode(',',"A,B,C,D,E,F,G,H,I");
        $arrHeader = array('会员账号','会员级别','会员姓名','手机号码','推荐账号','账户余额','团队台数','备注信息','加入时间');

        //填充表头信息
        $lenth =  count($arrHeader);
        for($i = 0;$i < $lenth;$i++) {
            $objActSheet->setCellValue("$letter[$i]1","$arrHeader[$i]");
        };


        //填充表格信息
        foreach($xlsData as $k=>$v){
            $LevelInfo = LevelInfo(['id'=>$v['level']]);
            $Recommend = UserInfo(['id'=>$v['recommend']]);
            $k +=2;
            $objActSheet->setCellValue('A'.$k,$v['username']." ");
            $objActSheet->setCellValue('B'.$k, $LevelInfo['name']);
            $objActSheet->setCellValue('C'.$k, $v['name']);
            $objActSheet->setCellValue('D'.$k, $v['phone']);
            $objActSheet->setCellValue('E'.$k, $Recommend['username']);
            $objActSheet->setCellValue('F'.$k, $v['balance_1']);
            $objActSheet->setCellValue('G'.$k, $v['team_num']);
            $objActSheet->setCellValue('H'.$k, $v['remark']);
            $objActSheet->setCellValue('I'.$k, date('Y-m-d H:i',$v['add_time']));
            // 表格高度
            $objActSheet->getRowDimension($k)->setRowHeight(20);

            $width = array(10,15,20,25,30);
            //设置表格的宽度
            $objActSheet->getColumnDimension('A')->setWidth($width[1]);
            $objActSheet->getColumnDimension('B')->setWidth($width[2]);
            $objActSheet->getColumnDimension('C')->setWidth($width[2]);
            $objActSheet->getColumnDimension('D')->setWidth($width[2]);
            $objActSheet->getColumnDimension('E')->setWidth($width[1]);
            $objActSheet->getColumnDimension('F')->setWidth($width[1]);
            $objActSheet->getColumnDimension('G')->setWidth($width[1]);
            $objActSheet->getColumnDimension('H')->setWidth($width[2]);
            $objActSheet->getColumnDimension('I')->setWidth($width[2]);
        }


        $outfile = "会员信息列表.xlsx";
        ob_end_clean();
        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header('Content-Disposition:inline;filename="'.$outfile.'"');
        header("Content-Transfer-Encoding: binary");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Pragma: no-cache");

        $objWriter->save('php://output');
    }

    /**
     * 会员网络图
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function NetMap(){
        $UserName = Param('username');
        $ContactNum = Param('contact_num');
        
        if(!empty($UserName)){ //根据用户名搜索
            $p_info = UserInfo(['username'=>$UserName]);
            $ContactInfo = Db::name('user_contact')->where(['user_id'=>$p_info['id'],'contact_id'=>$p_info['id'],'user_num'=>$ContactNum])->find();
            $UserNum = $ContactInfo['user_num'];
            if(empty($p_info)){
                $p_info = UserInfo(['id'=>1]);
                $ContactNum = 1;
                $UserNum = 1;
            }
        }else{
            $p_info = UserInfo(['id'=>1]);
            $ContactNum = 1;
            $UserNum = 1;
        }

        $LevelInfo = Db::name('user_level')->where(['id'=>$p_info['level']])->find();
        $p_info['level'] = $LevelInfo['name'];
        $p_info['contact_num'] = $ContactNum;
        $p_info['user_num'] = $UserNum;
       

        // //上层
        // $ContactInfo = Db::name("user_contact")->where(["user_id"=>$p_info['id'],'layer'=>1])->find();
        // $higher = UserInfo(['id'=>$ContactInfo['contact_id']]);
        // if(empty($higher)){
        //     $higher = UserInfo(['id'=>1]);
        // }
        // $this->assign('higher',$higher);

        $level_second_l = $this->find_left_right($p_info['id'],1,$p_info['user_num']);//次层左结点
        $level_second_r = $this->find_left_right($p_info['id'],2,$p_info['user_num']);//次层右结点


        $level_third_l1  = $this->find_left_right($level_second_l['id'],1,$level_second_l['user_num']);
        $level_third_r1 = $this->find_left_right($level_second_l['id'],2,$level_second_l['user_num']);



        $level_third_l2  = $this->find_left_right($level_second_r['id'],1,$level_second_r['user_num']);
        $level_third_r2  = $this->find_left_right($level_second_r['id'],2,$level_second_r['user_num']);

        $this->assign('p_info',$p_info);
        $this->assign('level_second_l',$level_second_l);
        $this->assign('level_second_r',$level_second_r);
        $this->assign('level_third_l1',$level_third_l1);
        $this->assign('level_third_r1',$level_third_r1);
        $this->assign('level_third_l2',$level_third_l2);
        $this->assign('level_third_r2',$level_third_r2);

        return $this->fetch('NetMap');
    }

    /**
     * 网络图左区右区用户
     * @param $node_id
     * @param $left_right
     * @param $ContactNum
     * @return array|false|\PDOStatement|string|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function  find_left_right($node_id,$left_right,$ContactNum)
    {
        $ContactInfo = Db::name("user_contact")->where(["contact_id"=>$node_id,'layer'=>1,"line"=>$left_right,'contact_num'=>$ContactNum])->find();
        $Info = UserInfo(['id'=>$ContactInfo['user_id']]);
        if(!empty($Info)){
            $LevelInfo = Db::name('user_level')->where(['id'=>$Info['level']])->find();
            $Info['level'] = $LevelInfo['name'];
            $Info['contact_num'] = $ContactInfo['contact_num'];
            $Info['user_num'] = $ContactInfo['user_num'];
        }
        return $Info;
    }

    /**
     * 会员推荐图
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function RecommendMap(){
        //查找的用户名
//        $UserName = Param('username');
//        if(empty($UserName)){
//            $UserName = "adminfssdsfs";
//        }
        //查找ID
        $id = Param('id');
        if(empty($id)){
            $id = "1";
        }
        //会员信息
//        $UserInfo = UserInfo(['username'=>$UserName]);
        $UserInfo = UserInfo(['id'=>$id]);
        if($UserInfo){
            $LevelInfo = LevelInfo(['id'=>$UserInfo['level']]);
            $UserInfo['level_name'] = $LevelInfo['name'];
            $Data = array('name' =>$UserInfo['username'].'|'.$UserInfo['level_name'].'|'.$UserInfo['id'],'children'=>$this->SelectSon($UserInfo['id']));       //父节点  Pid=1;
            $Data = json_encode($Data);
        }else{
            $Data = null;
        }
//dump($Data);die;
        $this->assign('id',$id);
        $this->assign("Data",$Data);
        return $this->fetch('RecommendMap');
    }

    /**
     * 推荐图寻找下级接点
     * @param $higher_id
     * @return array|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public  function SelectSon($Recommend){
        $Where['recommend'] = $Recommend;
        $UserList = Db::name('user')->where($Where)->select();
        if($UserList){  //查找该父ID下的子ID
            $Data = array();
            for ($i=0; $i < count($UserList) ; $i++)
            {
                $LevelInfo = LevelInfo(['id'=>$UserList[$i]['level']]);
                $UserList[$i]['level_name'] = $LevelInfo['name'];

                $da=array('name' =>$UserList[$i]['username'].'|'.$UserList[$i]['level_name'].'|'.$UserList[$i]['id'],'children'=>$this->SelectSon($UserList[$i]['id']));  //递归算法！

                array_push($Data, $da);//加入子节点数组
            };
            return $Data;//一次性返回子节点数组，他们成为同级子节点。
        } else{
            return null;
        }
    }
    
    //冻结用户
    public function userdong(){
        if(IsPost()){
            $id = Param()['id'];
            $info = Db::name('user')->where(['id'=>$id])->find();
            if($info){
                $data['status'] = 0;
                if(Db::name('user')->where(['id'=>$id])->update($data) !== false){
                    return ['status'=>1,'message'=>'冻结成功'];
                }else{
                    return ['status'=>0,'message'=>'冻结失败,请稍候再试'];
                }
            }else{
                return ['status'=>0,'message'=>'账号不存在'];
            }
        }
    }
    
    //激活用户
    public function userji(){
        if(IsPost()){
            $id = Param()['id'];
            $info = Db::name('user')->where(['id'=>$id])->find();
            if($info){
                $data['status'] = 1;
                if(Db::name('user')->where(['id'=>$id])->update($data) !== false){
                    return ['status'=>1,'message'=>'激活成功'];
                }else{
                    return ['status'=>0,'message'=>'激活失败,请稍候再试'];
                }
            }else{
                return ['status'=>0,'message'=>'账号不存在'];
            }
        }
    }
}
